package utils

import (
	"database/sql"
	"fmt"
	"github.com/go-sql-driver/mysql"
	"log"
	"os"
	"time"
)

var (
	Db  *sql.DB
	err error
)

func init() {
	// 配置详细日志输出（添加此行参数）
	cfg := mysql.Config{
		User:   "root",
		Passwd: "root123",
		Net:    "tcp",
		Addr:   "127.0.0.1:3306",
		DBName: "bookstore",
		Params: map[string]string{
			"charset":           "utf8mb4",
			"parseTime":         "True",
			"loc":               "Local",
			"interpolateParams": "true", // 关键参数：显示完整SQL
		},
	}
	// 设置驱动日志（增加日志前缀和格式）
	mysql.SetLogger(log.New(os.Stdout, "[MySQL] ", log.LstdFlags|log.Lshortfile))

	// 使用配置对象连接
	Db, err = sql.Open("mysql", cfg.FormatDSN())
	if err != nil {
		panic(err.Error())
	}
	fmt.Println("succwww")

	// 验证连接时显示更多信息
	Db.SetConnMaxLifetime(3 * time.Minute)
	if err = Db.Ping(); err != nil {
		log.Fatalf("Database connection failed: %v", err)
	}

	//Db, err = sql.Open("mysql", "root:root123@tcp(127.0.0.1:3306)/bookstore?charset=utf8mb4&parseTime=True&loc=Local")
	//if err != nil {
	//	panic(err.Error())
	//}
}
